# -*- coding: utf-8 -*-
'''
    此文件用于对数据库表baidu_stock_info的数据持久化操作
    封装对表的插入和更新操作
'''
import logging
from sqlalchemy import Column, String
from sqlalchemy.exc import IntegrityError
from baidustock.database import Base, DBBase, DBSession


logger = logging.getLogger(__name__)


class BaiduStockInfoTable(Base, DBBase):
    '''
        表''baidustockinfo''的持久化对象
    '''
    __tablename__ = 'baidustockinfo'

    stock_ID = Column('stock_ID', String(255), primary_key=True)
    opening_price = Column('opening_price', String(255))
    closing_price = Column('closing_price', String(255))
    maximun_price = Column('maximun_price', String(255))
    minimun_price = Column('minimun_price', String(255))
    turnover_total = Column('turnover_total', String(255))
    turnover_volume = Column('turnover_volume', String(255))
    turnover_rate = Column('turnover_rate', String(255))
    efamc = Column('efamc', String(255))
    mktcap = Column('mktcap', String(255))

    @classmethod
    def insert(cls, obj):
        '''
            插入对象，
            1.对象不存在，直接插入
            2.对象存在，则更新
        '''
        with DBSession() as session:
            try:
                session.add(obj)
                session.flush()
            except IntegrityError, e:
                logger.info(e.message)
                # 如果该主键值已经存在，就更新该数据
                if 'Duplicate' in e.message:
                    session.rollback()
                    logger.info('Records exists')
                    cls.update(obj)
                # 如果是其他的问题，就把异常继续向上抛
                else:
                    raise e

    @classmethod
    def update(cls, obj):
        '''
        用当前的对象更新数据
        :return:
        '''
        with DBSession() as session:
            record = session.query(cls).filter(
                cls.stock_ID == obj.stock_ID
            ).one()
            if record.mktcap != obj.mktcap:
                logger.info('Update data {0}'.format(record.stock_ID))
                session.delete(record)
                session.add(obj)
                session.flush()
